<?php


namespace App\Services\Base;

/**
 * Class MsgService
 * @package App\Services
 * 消息定义
 */
class MsgService
{

    private static $default_lang = "en";
    private static $lang_enabled = [
        "en" => "英文",
        "zh_TW" => "繁体中文",
        "zh_CN" => "中文",
    ];

    private static $lang_map = [
        'zh' => "zh_CN",
        'zh-CN' => "zh_CN",
        'hk' => "zh_TW",
        'tw' => "zh_TW",
    ];

    public static function getLang($request)
    {
        $lang = $request->header("Lang", self::$default_lang);
        $lang = self::mapLang($lang);
        if (!array_key_exists($lang, self::$lang_enabled)) {
            $lang = self::$default_lang;
        }

        return $lang;
    }

    /**
     * 转换客户端简写语言标记，如zh -> zh_CN
     * @param $lang_source
     * @return string
     */
    public static function mapLang($lang_source)
    {
        return self::$lang_map[$lang_source] ?? $lang_source;
    }

    //错误定义
    public static function error($code = null)
    {
        $errors = [
            401 => '访问拒绝',
            400 => '不允许的请求',
            404 => '不存在的请求',
            405 => '系统异常',
            406 => '数据库异常',
            407 => '缓存异常',
            408 => '参数不完整',
            409 => '数据不存在',
            410 => '参数错误',
            411 => '操作失败',
            412 => '验证码不能为空',
            413 => '验证码已过期或不存在',
            414 => '验证码错误',
            415 => '数据已存在',
            416 => '操作太频繁',
            417 => '系统异常', //这个异常是人为调用API引起
            418 => '认证失效，请重新返回认证',
            419 => '内部通信错误',
            420 => '太久没有操作，请重新发起',
            421 => '验证方式有误',

            1000 => '邮箱不能为空',
            1001 => '手机号不能为空',
            1002 => '推荐人不存在',
            1003 => '邮箱已存在',
            1004 => '手机号已存在',
            1005 => '用户不存在',
            1006 => '密码错误',
            1007 => '用户被禁用',
            1008 => '旧密码错误',
            1009 => '密码规则出错',
            1010 => '两次密码不一致',
            1011 => '请设置支付密码',
            1012 => '手机格式有误',
            1013 => '邮箱格式有误',
            1014 => '谷歌验证码错误',
            1015 => '邮箱已绑定无法再次绑定',
            1016 => '手机已绑定无法再次绑定',
            1017 => '谷歌验证码已绑定',
            1018 => '支付方式已存在',
            1019 => '余额不足',
            1020 => '链不存在',
            1021 => '邀请人已存在',
            1022 => '邮箱未开通',
            1023 => '电话未开通',
        ];

        if(is_null($code)) {
            return $errors;
        } else {
            return $errors[$code] ?? null;
        }
    }

    /**
     * @param int $code 错误编码
     * @param array $attributes
     * @param $lang
     * @return array|string|null
     */
    public static function toMessage($code, $attributes = [], $lang = null)
    {
        $lang = $lang ?: app()->getLocale();
        $_error = self::error($code) ?? false;
        return __($_error ?: "系统错误", $attributes, $lang);
    }

    /**
     * @return string[]
     */
    public static function getLangList()
    {
        return self::$lang_enabled;
    }

}
